#include "OTA_task.h"


esp_err_t err = ESP_OK;
esp_ota_handle_t update_handle = 0;
const esp_partition_t *update_partition = NULL;


void OTA_init()
{
    update_partition = esp_ota_get_next_update_partition(NULL);                                         //获取下一个OTA更新的区域
    err = esp_ota_begin(update_partition,OTA_SIZE_UNKNOWN, &update_handle);                             //安装OTA升级
    if(err != ESP_OK) //进入OTA模式失败，自动重启
    {
        LOG_INFO("esp_ota_begin failed!\n");
        esp_restart();
    }
}

void OTA_write(u8 *buffer,u16 length)
{
    err  = esp_ota_write(update_handle, (const void *)buffer,length);  //往flash写入数据
    printf("OTA length is %d\n",length);
    if (err != ESP_OK) //若是写入失败，则进入重启
    {
        LOG_INFO("Error: esp_ota_write failed! err = 0x%x\n", err);
        esp_restart();
    }

}


void OTA_finish()
{
    if(esp_ota_end(update_handle) != ESP_OK) 
    {
        LOG_INFO("esp_ota_end failed!\n");
    }
    else
    {
        err = esp_ota_set_boot_partition(update_partition);
        if(err != ESP_OK) 
        {
            LOG_INFO("esp_ota_set_boot_partition failed! err=0x%x\n",err);
        }
    }
    LOG_INFO("OTA_finish()\n");
    esp_restart();
}